<template>
   <div class="glad-container">
     <slot></slot>
   </div>
</template>

<script lang='ts'>
import { computed, defineComponent } from 'vue'

export default defineComponent({
  name: 'ChuForm',
  props: {
    cols: {
      type: [String, Number],
      default: 2
    }
  },
  setup (props) {
    const columns = computed(() => {
      const className = 'row-cols-' + props.cols
      const classObj: { [k: string]: boolean } = {}
      classObj[className] = true
      return classObj
    })

    const formCheckData: Array<FormCheckData> = []

    const checkAsync = async (include: Array<string> = [], exclude: Array<string> = []) => {
      // 当有include时，只看include
      // 当include无值时，exclude才有效
      const asyncArr: Array<Promise<ValRes>> = []
      formCheckData.forEach((formCheckDataItem) => {
        const { validate, formId } = formCheckDataItem
        if (include.length > 0 && formId) {
          if (!include.includes(formId)) {
            // 不需要校验，跳过
            asyncArr.push(Promise.resolve({ res: true }))
            return
          }
        } else if (exclude.length > 0 && formId) {
          if (exclude.includes(formId)) {
            // 不需要校验，跳过
            asyncArr.push(Promise.resolve({ res: true }))
            return
          }
        }
        const checkPro = () => new Promise<ValRes>((resolve) => {
          resolve(validate())
        })
        asyncArr.push(checkPro())
      })
      // 这里会返回结果数组
      return Promise.all(asyncArr)
    }
    // 表单校验
    const formCheck: FormCheckFun = async (conditions?: ConditionProp) => {
      let include, exclude
      if (conditions) {
        include = conditions.include
        exclude = conditions.exclude
      }
      const checkResArr: Array<ValRes> = await checkAsync(include, exclude)
      console.log('checkResArr: ', checkResArr)
      const checkRes = checkResArr.every(checkRes => checkRes.res)
      const errRes = checkResArr.find((item) => {
        return item.res === false
      })
      const message = errRes ? errRes.message : ''
      return { checkRes, message }
    }
    // 创建监听
    chu.listener.on<FormCheckData>('form-item-created', (validator) => {
      if (validator) {
        formCheckData.push(validator)
      }
    })
    return {
      columns,
      formCheck
    }
  }
})
</script>

 <style scoped>
 .glad-container {
  padding: 2vh;
}
 </style>
